package com.one.group.admin.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.one.group.admin.mapper.VehicleMapper;
import com.one.group.admin.mapper.VehicleSpaceMapper;
import com.one.group.enums.ErrorCode;
import com.one.group.exception.BusinessException;
import com.one.group.model.dto.VehicleAddDto;
import com.one.group.model.dto.VehicleQueryDto;
import com.one.group.model.entity.Vehicle;
import com.one.group.model.entity.VehicleSpace;
import com.one.group.model.vo.VehicleListVo;
import com.one.group.model.vo.VehicleSearchVo;
import com.one.group.service.VehicleService;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.convert.Convert;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.Date;
import java.util.List;

@DubboService
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;

    @Autowired
    private VehicleSpaceMapper vehicleSpaceMapper;

    @Override
    public List<VehicleListVo> findVehicleByQueryDto(VehicleQueryDto vehicleQueryDto) {
        //获取当前租户id
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));
        vehicleQueryDto.setTenantId(tenantId);
        return vehicleMapper.findVehicleByQueryDto(vehicleQueryDto);
    }

    @Override
    public boolean addVehicle(VehicleAddDto vehicleAddDto) {
        // 获取租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));

        // 检查车牌号是否已存在
        Vehicle existingVehicle = vehicleMapper.selectOneByPlateNoAndCellId(
                vehicleAddDto.getPlateNo(), vehicleAddDto.getCellId(), tenantId);
        if (existingVehicle != null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该小区下已存在相同车牌号的车辆");
        }

        // 创建车辆实体
        Vehicle vehicle = new Vehicle();
        vehicle.setCellId(vehicleAddDto.getCellId());
        vehicle.setPlateNo(vehicleAddDto.getPlateNo());
        vehicle.setOwnerName(vehicleAddDto.getOwnerName());
        vehicle.setContactPhone(vehicleAddDto.getContactPhone());
        vehicle.setOwnerType(vehicleAddDto.getOwnerType());
        vehicle.setRemark(vehicleAddDto.getRemark());
        vehicle.setCreatedTime(new Date());
        vehicle.setUpdatedTime(new Date());
        vehicle.setTenantId(tenantId);

        return save(vehicle);
    }

    @Override
    public boolean deleteVehicle(Long id) {
        // 获取租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));

        // 检查车辆是否存在
        Vehicle vehicle = getById(id);
        if (vehicle == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "车辆不存在");
        }

        // 检查租户权限
        if (!vehicle.getTenantId().equals(tenantId)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作该车辆");
        }

        // 先删除该车辆的所有绑定记录
        QueryWrapper queryWrapper = QueryWrapper.create().from(VehicleSpace.class);
        queryWrapper.eq(VehicleSpace::getVehicleId, id)
                   .eq(VehicleSpace::getTenantId, tenantId);
        vehicleSpaceMapper.deleteByQuery(queryWrapper);

        // 删除车辆本身
        return removeById(id);
    }

    @Override
    public boolean batchDeleteVehicles(List<Long> ids) {
        // 获取租户ID
        Long tenantId = Convert.toLong(StpUtil.getExtra("tenant_id"));

        // 逐个检查车辆
        for (Long id : ids) {
            Vehicle vehicle = getById(id);
            if (vehicle == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "车辆ID " + id + " 不存在");
            }

            // 检查租户权限
            if (!vehicle.getTenantId().equals(tenantId)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限操作车辆ID " + id);
            }
        }

        // 先删除所有车辆对应的绑定记录
        QueryWrapper queryWrapper = QueryWrapper.create().from(VehicleSpace.class);
        queryWrapper.in(VehicleSpace::getVehicleId, ids)
                   .eq(VehicleSpace::getTenantId, tenantId);
        vehicleSpaceMapper.deleteByQuery(queryWrapper);

        // 批量删除车辆
        return removeByIds(ids);
    }

    @Override
    public List<VehicleSearchVo> searchVehiclesByPlateNo(String plateNo) {
        // 获取当前租户ID
        String tenantId1 = RpcContext.getContext().getAttachment("tenantId");
        Long tenantId = null;
        if (tenantId1 != null && !tenantId1.isEmpty()) {
            try {
                tenantId = Long.valueOf(tenantId1);
            } catch (NumberFormatException e) {
                // 处理无效格式
                e.printStackTrace();
            }
            return vehicleMapper.searchVehiclesByPlateNo(plateNo, tenantId);
        } else {
            tenantId = Convert.toLong(tenantId1);
            return vehicleMapper.searchVehiclesByPlateNo(plateNo, tenantId);
        }

    }
}
